import {
    checkDepartmentCodeUnique,
    checkDepartmentNameUnique,
    addDepartment
} from "@/api/departmentApi";

export default {
    data() {
        // 自定义验证函数
        const validateCode = (rule, value, callback) => {
            const pattern = /^[A-Z]{0,5}$/; // 只允许大写字母，最多5个字符
            if (!pattern.test(value)) {
                callback(new Error("部门编号只能是大写字母且不能超过5位"));
            } else {
                callback();
            }
        };

        const validateName = (rule, value, callback) => {
            // 验证是否以字母开头、结尾没有空格
            const startAndEndPattern = /^[A-Za-z].*[^\s]$/;

            // 验证是否包含至少一个字母
            const letterPattern = /[A-Za-z]/;

            // 验证整个字符串的格式：只能包含字母、数字和空格
            const formatPattern = /^[A-Za-z0-9 ]{1,30}$/;

            if (!formatPattern.test(value)) {
                callback(new Error("部门名称只能包含字母、数字和空格，且长度不能超过30个字符"));
            } else if (!letterPattern.test(value)) {
                callback(new Error("部门名称必须包含至少一个字母"));
            } else if (!startAndEndPattern.test(value)) {
                callback(new Error("部门名称必须以字母开头且结尾不能有空格"));
            } else {
                callback();
            }
        };

        return {
            department: {
                name: '',
                code: '',
                remarks: ''
            },
            rules: {
                name: [
                    { required: true, message: '部门名称不能为空', trigger: 'blur' },
                    { validator: validateName, trigger: 'blur' }
                ],
                code: [
                    { required: true, message: '部门编号不能为空', trigger: 'blur' },
                    { validator: validateCode, trigger: 'blur' }
                ],
                remarks: [
                    { required: true, message: '部门职能不能为空', trigger: 'blur' },
                    { max: 300, message: '部门职能不能超过300个字符', trigger: 'blur' }
                ]
            }
        };
    },
    methods: {
        async insertDeptInfo() {
            try {
                const result = await addDepartment(this.department.code, this.department.name, this.department.remarks);
                if (result.code === 200) {
                    this.$message({
                        message: '添加成功',
                        type: 'success'
                    });
                    this.$router.push({ path: '/department/DepartmentList' });
                } else {
                    this.$message({
                        message: '添加失败',
                        type: 'error'
                    });
                }
            } catch (error) {
                console.error('加载数据失败:', error);
                this.$alert('网络错误，请稍后再试', '提示', {
                    confirmButtonText: '确定'
                });
            }
        },
        async checkDeptNameUnique() {
            try {
                const deptResult = await checkDepartmentNameUnique(this.department.name);
                if (deptResult.code === 200) {
                    if (deptResult.data) {
                        this.$message({
                            message: '部门名称已存在',
                            type: 'error'
                        });
                    } else {
                        this.insertDeptInfo();
                    }
                }
            } catch (error) {
                console.error('加载数据失败:', error);
                this.$alert('网络错误，请稍后再试', '提示', {
                    confirmButtonText: '确定'
                });
            }
        },
        async onSubmit() {
            // 先进行表单验证
            this.$refs.departmentForm.validate(async (valid) => {
                if (valid) {
                    try {
                        const deptResult = await checkDepartmentCodeUnique(this.department.code);
                        if (deptResult.code === 200) {
                            if (deptResult.data) {
                                this.$message({
                                    message: '部门编号已存在',
                                    type: 'error'
                                });
                            } else {
                                await this.checkDeptNameUnique();
                            }
                        }
                    } catch (error) {
                        console.error('加载数据失败:', error);
                        this.$alert('网络错误，请稍后再试', '提示', {
                            confirmButtonText: '确定'
                        });
                    }
                } else {
                    this.$message({
                        message: '请修正表单中的错误',
                        type: 'error'
                    });
                    return false;
                }
            });
        },
        resetForm() {
            this.$refs.departmentForm.resetFields();
        },
        goBack() {
            this.$router.replace({path: '/Department/DepartmentList'});
        }
    }
};